package com.czk.config;

import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;

import java.io.Serializable;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/18 14:56
 */
public class OwnIdGenerator extends IdentityGenerator {
    Random random = new Random();
    Lock lock = new ReentrantLock();

    @Override
    public Serializable generate(SharedSessionContractImplementor s, Object obj) {
        System.out.println("=====OwnIdGenerator===触发了");
        try {
            lock.lock();
            // 这里随便生成一个i,当然可能重复
            int i = random.nextInt();
            return i;
        } finally {
            lock.unlock();
        }
    }
}
